
import { View } from "@tarojs/components";
import Taro from "@tarojs/taro";

import ByCell from "@/components/ui/ByCell";
import ByAvatar from "@/components/ui/ByAvatar";
import ByButton from "@/components/ui/ByButton";
import ByCellGroup from "@/components/ui/ByCellGroup";

import { clearLoginInfo } from "@/api/login";
import useFetch from "@/hooks/useFetch";
import useAppStore from "@/store";
import ApiUser from "@/api/user";

const cellProps = {
  align: "right",
  size: "small",
} as const;

export default () => {
  const userInfo = useAppStore((state) => state.userInfo);

  const { loading, run } = useFetch(ApiUser.unbind, "POST", {
    manual: true,
    onSuccess() {
      clearLoginInfo();
      Taro.showToast({ title: "解绑成功！" });
      setTimeout(() => {
        Taro.reLaunch({ url: "/pages/login/index" });
      }, 1500);
    },
  });

  const handleUnbind = async () => {
    const { confirm } = await Taro.showModal({
      title: "解除绑定",
      content: "解绑后，需要重新登录方可使用；其他微信可绑定本账号",
    });

    if (confirm) {
      const { code } = await Taro.login();
      run({ code });
    }
  };

  return (
    userInfo && (
      <View className="h-screen flex flex-col">
        <View className="flex-auto px-6">
          <View className="py-6 text-center">
            <ByAvatar
              src=""
              alt={userInfo.user_name}
              className="bg-primary text-white"
              size={120}
            />

            <View className="mt-3 font-bold text-lg">{userInfo.user_name}</View>
            <View className="mt-2 text-sm text-second">
              {userInfo.post_names}
            </View>
          </View>

          <ByCellGroup>
            <View className="p-3">
              <ByCell {...cellProps} label="企业">
                {userInfo.org_name}
              </ByCell>
              <ByCell {...cellProps} label="部门">
                {userInfo.dept_name}
              </ByCell>
              <ByCell {...cellProps} label="角色">
                {userInfo.role_names}
              </ByCell>
              <ByCell {...cellProps} label="账号">
                {userInfo.user_code}
              </ByCell>
              <ByCell {...cellProps} label="联系方式">
                {userInfo.mobile_tel}
              </ByCell>
            </View>
          </ByCellGroup>
        </View>
        <View className="flex-none px-6 py-3">
          <ByButton
            round
            type="error"
            size="large"
            loading={loading}
            variant="outline"
            onClick={handleUnbind}
          >
            解绑账号
          </ByButton>

          <View className="safe-footer" />
        </View>
      </View>
    )
  );
};
